<template>
  <plain-page>
    <el-card shadow="never" body-style="padding: 10px">
      <el-form inline :model="queryForm">
        <el-form-item label="社区">
          <org-check-tree
            v-model="queryForm.orgIds"
            :check-strictly="false"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" plain @click="onQueryClick">查询</el-button>
        </el-form-item>
        <el-form-item label="排序">
          <type-select v-model="selectedMajor" :items="getMajorOptions" style="width:140px;" />
          <type-select
            v-model="selectedMinor"
            :items="selectedMajor && majorDictMap ? DictMan.items(majorDictMap[selectedMajor]) : null"
            style="width:140px;"
          />
          <radio-options v-model="order" :options="DictMan.items('sortOrder')" clearable style="width:132px;" />
        </el-form-item>
        <el-form-item label="颜色深浅" class="color-option">
          <el-switch
            v-model="colorLightEnabled"
            active-color="#fda2a2"
          />
        </el-form-item>
        <el-form-item label="非0数高亮颜色" class="color-option">
          <el-switch
            v-model="hightlightEnabled"
            active-color="#fda2a2"
          />
        </el-form-item>
      </el-form>
    </el-card>
    <el-card
      shadow="never"
      body-style="padding: 0px;height: calc(100vh - 164px);overflow-x: scroll;"
      :element-loading-text="loadingText"
      v-loading="loading"
      style="margin-top: 2px"
    >
      <table cellspacing="0" cellpadding="0">
        <thead v-if="majorDictMap">
          <tr>
            <th rowspan="2">序号</th>
            <th rowspan="2">社区</th>
            <th rowspan="2">总人数</th> 
            <th 
              v-for="(title, major) in majorTitleMap"
              :key="major"
              :colspan="dictItemsByMajor(major).length">{{title}}</th>
          </tr>
          <tr>
            <template v-for="(title, major) in majorTitleMap">
              <th v-for="item in dictItemsByMajor(major)" :key="major+item.value">
                {{item.text}}
              </th>
            </template>
          </tr>
        </thead>
        <tbody v-if="majorDictMap && data">
          <tr v-for="(row, index) in data" :key="index" @click="onChartClick(row)">
            <td>{{data.length - index}}</td>
            <td><el-link type="primary" icon="el-icon-data-analysis"></el-link> {{row.orgName}}</td>
            <td class="number-cell" :title="`总人数为${getCount(row, 'total')}`" :style="getCellStyle(row, 'total')">{{row.total}}</td>
            <template v-for="(title, major) in majorTitleMap">
              <td
                v-for="item in dictItemsByMajor(major)"
                :key="major + item.value"
                :title="`在【${row.orgName}】社区中【${title}】是【${item.text}】的人数为 ${getCount(row, major, item)}`"
                class="number-cell"
                :style="getCellStyle(row, major, item)"
              >
                <div v-if="getCount(row, major, item)">{{getCount(row, major, item)}}</div>
                <div v-else></div>
              </td>
            </template>
          </tr>
        </tbody>
      </table>
      <div
        v-show="noData"
        style="padding: 200px 0px;text-align: center;"
      >
        未查询到数据
      </div>
    </el-card>
  </plain-page>
</template>

<script>
import RadioOptions from '@/components/RadioOptions';
import OrgCheckTree from '@/pages/org/OrgCheckTree';
import { majorTitleMap } from './dicts';

export default {
  pageProps: {
    title: '社区用户数据汇总'
  },
  components: {
    RadioOptions,
    OrgCheckTree
  },
  data() {
    return {
      loading: true,
      hightlightEnabled: false,
      colorLightEnabled: true,
      
      selectedMajor: 'total',
      selectedMinor: '',
      order: 'desc',
      queryForm: {
        orderBy: [
          ['total', 'desc']
        ],
        orgIds: []
      },
      noData: false,
      data: null,
      majorDictMap: null,
      majorTitleMap
    };
  },
  computed: {
    getMajorOptions() {
      let opts = [];
      opts.push({value: 'total', text: '总人数'});
      for (let major in this.majorTitleMap)
        opts.push({value: major, text: this.majorTitleMap[major]});
      return opts;
    },
    loadingText() {
      return app.admin.roleId == 1 ? '数据量较大，请稍等' : '汇总中，请稍等';
    }
  },
  watch: {
    loading() {
      this.hightlightEnabled = true;
    },
    hightlightEnabled(v) {
      this.colorLightEnabled = v;
    },
    selectedMajor(major) {
      this.selectedMinor = null;
      if (!major) return;

      if (this.order && (major == 'total' || (major != 'total' && this.selectedMinor))) {
        this.addOrderBy();
        this.query();
      }
    },
    selectedMinor(minor) {
      if (!minor) return;

      if (this.order && this.selectedMajor) {
        this.addOrderBy();
        this.query();
      }
    },
    order(order) {
      if (order) {
        if (this.selectedMajor == null || (this.selectedMajor != 'total' && !this.selectedMinor)) return;
        this.addOrderBy();
        this.query();
      } else {
        this.removeOrderBy();
        this.query();
      }
    }
  },
  async mounted() {
    await this.query();
  },
  methods: {
    getCount(row, major, dictItem) {
      return major == 'total' ? row.total : (row.itemsMap[major] && row.itemsMap[major][dictItem.value]) || 0;
    },
    dictItemsByMajor(major) {
      return DictMan.items(this.majorDictMap[major]);
    },
    getCellStyle(row, major, dictItem) {
      if (!this.hightlightEnabled) return null;
      let count = this.getCount(row, major, dictItem);
      if (count == 0) return null;
      if (!this.colorLightEnabled) {
        if (major == 'total') return null;
        return {
          background: 'rgb(255, 230, 230)'
        };
      }
      let [min, max] = this.colMinMaxMap[major == 'total' ? 'total' : major + dictItem.value];
      if (min == max) {
        return {
          background: 'rgb(255, 230, 230)'
        };
      }
      let g = (1 - Math.max(0.1, (count - min) / (max - min))) * 235 + 20;
      return {
        background: `rgb(255,${g},${g})`,
        color: g < 200 ? '#fafafa' : null
      };
    },
    onQueryClick() {
      this.query();
    },
    onChartClick(row) {
      this.pushPage({
        path:'/stat/user-stat',
        key: row.orgId,
        params: {
          query: {
            orgIds: row.orgId
          }
        },
        subTitle: row.orgName
      });
    },
    addOrderBy() {
      let orderByItem = this.selectedMajor == 'total'
        ? [this.selectedMajor, this.order]
        : [this.selectedMajor, this.selectedMinor, this.order]
      this.queryForm.orderBy = [orderByItem];
    },
    removeOrderBy() {
      this.queryForm.orderBy = [];
    },
    async query() {
      let queryParams = {...this.queryForm};
      queryParams.orderBy = queryParams.orderBy.map(item => item.join(' ')).join(',');
      if (queryParams.orgIds && queryParams.orgIds instanceof Array) {
        queryParams.orgIds = queryParams.orgIds.join(',');
      }

      this.loading = true;
      let ret = await this.$http.get('/api/user/stat/org-user-stat', {params: queryParams, timeout: 15000});
      let { records } = ret;
      this.majorDictMap = ret.majorDictMap;
      let colMinMaxMap = {};

      for (let row of records) {
        for (let major in row.itemsMap) {
          for (let minor in row.itemsMap[major]) {
            let count = row.itemsMap[major][minor];        
            let [min, max] = colMinMaxMap[major + minor] || [count, count];
            if (count < min)
              min = count;
            if (count > max)
              max = count;
            colMinMaxMap[major + minor] = [min, max];
          }
        }

        let [min, max] = colMinMaxMap['total'] || [row.total, row.total];
        if (row.total < min)
          min = row.total;
        if (row.total > max)
          max = row.total;
        colMinMaxMap['total'] = [min, max];
      }
      this.colMinMaxMap = colMinMaxMap;
      this.data = records;
      this.loading = false;
      if (records.length == 0) {
        setTimeout(() => {
          this.noData = true;
        }, 500);
      }
    }
  },

}
</script>

<style scoped>
table {
  border-collapse: collapse;
  overflow: hidden;
}
table thead {
  background: #f5f7fa;
  color: #909399;
  user-select: none;
}
table th, table td {
  padding: 6px 8px;
  border: 1px solid #E4E7ED;
  font-size: 14px;
  white-space: nowrap;
}
table td {
  color: #606266;
}
table td.number-cell {
  transition: 0.35s background ease-out;
  text-align: center;
}

table td.number-cell:hover {
  background: rgb(255, 230, 230) !important;
  font-weight: bold;
}
table tbody > tr:hover {
  background: #F2F6FC;
}
table tbody tr:nth-child(even) {
  background: #FAFAFA;
}
>>> .el-form-item__label {
  padding-right: 8px;
}
>>> .el-form-item {
  margin-bottom: 0px;
}

>>> .el-form-item.color-option {
  float: right;
}
@media screen and (max-width: 1260px) {
  .color-option {
    display: none;
  }
}
</style>